package com.wangdong.mvpretrofitokhttprxjava.base;


import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;


import com.hjq.toast.ToastUtils;
import com.wangdong.mvpretrofitokhttprxjava.R;
import com.wangdong.mvpretrofitokhttprxjava.common.AppStatusConstant;
import com.wangdong.mvpretrofitokhttprxjava.manager.AppStatusManager;
import com.wangdong.mvpretrofitokhttprxjava.model.BaseModel;
import com.wangdong.mvpretrofitokhttprxjava.presenter.BasePresenter;
import com.wangdong.mvpretrofitokhttprxjava.utils.KeyBoardUtils;
import com.wangdong.mvpretrofitokhttprxjava.utils.StatusBarUtil;
import com.wangdong.mvpretrofitokhttprxjava.view.MainActivity;
import com.wangdong.mvpretrofitokhttprxjava.view.dialog.LoadingDialog;
import com.wangdong.mvpretrofitokhttprxjava.view.dialog.ProgressDialog;

import butterknife.ButterKnife;

/**
 * @author 53007
 * @param <P>
 */
public abstract class BaseActivity<P extends BasePresenter> extends AppCompatActivity implements BaseView {


    protected final String TAG = this.getClass().getSimpleName();
    public Context mContext;
    protected P mPresenter;

    protected abstract P createPresenter();

    private LoadingDialog loadingDialog;
    private ProgressDialog progressDialog;


    public TextView mBackName;
    public LinearLayout mBack;
    public TextView mTvTitle;
    public TextView mTvRight;
    public RelativeLayout mRltBase;

    protected View rootView;

    /**
     * 设置 沉浸式
     *  为了让客户感受更好的体验效果,所以我们会选择设置沉浸式,
     *  每个页面大多数都会设置一种效果,所以直接在BaseActivity设置即可
     *  如果不想设置此效果,在对应Activity中重写setStatusBar()
     */
    protected void setStatusBar(){
        /**设置状态颜色*/
       //StatusBarUtil.setColor(this,getResources().getColor(R.color.colorAccent),0);
        /**设置布局沉浸式,状态栏透明 透明度 0 ,向下偏移null*/
        StatusBarUtil.setTranslucentForImageViewInFragment(this,0,null);


    }


    /**
     * 屏幕横屏不切换 AndroidManifest中将不用再写 android:screenOrientation = "portrait"
     * 设置了反而会出现更多问题，其次说一下8.0更新问题，页面同时设置了android:screenOrientation="portrait"和透明属性，
     * 8.0运行会出现Only fullscreen opaque activities can request orientation异常，
     * 大概意思为“只有不透明的全屏activity可以自主设置界面方向”，我们或许会引用一些第三方SDK到项目中，也许第三方会用到透明属性，
     * 我们可能在AndroidManifest中会申明android:screenOrientation="portrait"后导致莫名其妙的奔溃（小概率事件，但不排除），
     * 所以建议在BaseActivity设置比较优（当你做侧滑返回以后就不会觉得我说这么啰嗦了）
     * 设置屏幕横竖屏切换
     *
     * @param screenRoate true 竖屏 fasle 横屏
     */
    private void setScreenRoate(Boolean screenRoate){
        if (screenRoate){
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        initAppStatus();
        setStatusBar();
        setScreenRoate(true);
        if (getLayoutId()!=0){
            rootView = View.inflate(this, R.layout.activity, null);
            addContent();
            setContentView(rootView);
            mPresenter = createPresenter();
            this.initData();
        }
    }

    private void addContent() {
        mBackName = (TextView) rootView.findViewById(R.id.back_name);
        mBack = (LinearLayout) rootView.findViewById(R.id.back);
        mTvTitle = (TextView) rootView.findViewById(R.id.tv_title);
        mTvRight = (TextView) rootView.findViewById(R.id.tv_right);
        mRltBase = (RelativeLayout) rootView.findViewById(R.id.rlt_base);
        FrameLayout flContent = (FrameLayout) rootView.findViewById(R.id.fl_content);

        mTvTitle.setText(getContentTitle() == null ? "" : getContentTitle());
        //mBack.setOnClickListener(v -> finish());//java8写法，特此备注一下
        mBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        View content = View.inflate(this, getLayoutId(), null);
        if (content != null) {
            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,
                    FrameLayout.LayoutParams.MATCH_PARENT);
            flContent.addView(content, params);
            ButterKnife.bind(this, rootView);
        }
    }
    /**
     * 获取布局ID
     *
     * @return
     */
    protected abstract int getLayoutId();

    /**
     * 数据初始化操作
     */
    protected abstract void initData();



    /**
     * 封装toast方法（自行定制实现）
     *
     * @param str
     */
    public void showToast(String str) {
        ToastUtils.show(str);
    }

    public void showLongToast(String str) {
        ToastUtils.show(str);
    }

    @Override
    public void showError(String msg) {
        showToast(msg);
    }

    /**
     * 返回所有状态  除去指定的值  可设置所有（根据需求）
     *
     * @param model
     */
    @Override
    public void onErrorCode(BaseModel model) {
        if (model.getError_code() == 10000000) {
            //处理些后续逻辑   如果某个页面不想实现  子类重写这个方法  将super去掉  自定义方法
//            App.put();
//            startActivity(LoginActivity.class);
        }
    }

    @Override
    public void showLoading() {
        showLoadingDialog();
    }

    @Override
    public void hideLoading() {
        dissMissDialog();
    }

    public void showLoadingDialog() {
        showLoadingDialog("加载中...");
    }

    /**
     * 加载  黑框...
     */
    public void showLoadingDialog(String msg) {
        if (loadingDialog == null) {
            loadingDialog = new LoadingDialog(this);
        }
        loadingDialog.setMessage(msg);
        if (!loadingDialog.isShowing()) {
            loadingDialog.show();
        }
    }

    /**
     * 消失  黑框...
     */
    public void dissMissDialog() {
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) {
            mPresenter.detachView();
        }
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
        if (mPresenter != null) {
            mPresenter.detachView();
        }
        if (getLayoutId()!=0) {
            ButterKnife.bind(this, rootView).unbind();
        }
    }


    /**
     * 显示下载进度
     */
    @Override
    public void showProgress() {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(this);
        }
        progressDialog.getProgressBar().performAnimation();
        if (!progressDialog.isShowing()) {
            progressDialog.show();
        }
    }

    /**
     * 隐藏下载进度
     */
    @Override
    public void hideProgress() {
        if (progressDialog != null) {
            progressDialog.getProgressBar().releaseAnimation();
            progressDialog.dismiss();
        }
    }

    /**
     * 下载进度
     * @param progress
     */
    @Override
    public void onProgress(int progress) {
        if (progressDialog != null) {
            progressDialog.updateProgress(progress);
        }
    }

    /**
     * [页面跳转]
     *
     * @param clz
     */
    public void startActivity(Class<?> clz) {
        startActivity(clz, null);
    }


    /**
     * [携带数据的页面跳转]
     *
     * @param clz
     * @param bundle
     */
    public void startActivity(Class<?> clz, Bundle bundle) {
        Intent intent = new Intent();
        intent.setClass(this, clz);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
    }

    /**
     * [含有Bundle通过Class打开编辑界面]
     *
     * @param cls
     * @param bundle
     * @param requestCode
     */
    public void startActivityForResult(Class<?> cls, Bundle bundle, int requestCode) {
        Intent intent = new Intent();
        intent.setClass(this, cls);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivityForResult(intent, requestCode);
    }


    private void initAppStatus() {
        switch (AppStatusManager.getInstance().getAppStatus()) {
            /**
             * 应用被强杀
             */
            case AppStatusConstant.STATUS_FORCE_KILLED:
                //跳到主页,主页lauchmode SINGLETASK
                protectApp();
                break;
            default:
                break;
        }
    }
    protected void protectApp() {
        Intent intent = new Intent(this, MainActivity.class);
        intent.putExtra(AppStatusConstant.KEY_HOME_ACTION, AppStatusConstant.ACTION_RESTART_APP);
        startActivity(intent);
    }



    protected abstract String getContentTitle();

    /**
     * 以下是关于软键盘的处理
     */

    /**
     * 清除editText的焦点
     *
     * @param v   焦点所在View
     * @param ids 输入框
     */
    public void clearViewFocus(View v, int... ids) {
        if (null != v && null != ids && ids.length > 0) {
            for (int id : ids) {
                if (v.getId() == id) {
                    v.clearFocus();
                    break;
                }
            }
        }
    }

    /**
     * 隐藏键盘
     *
     * @param v   焦点所在View
     * @param ids 输入框
     * @return true代表焦点在edit上
     */
    public boolean isFocusEditText(View v, int... ids) {
        if (v instanceof EditText) {
            EditText et = (EditText) v;
            for (int id : ids) {
                if (et.getId() == id) {
                    return true;
                }
            }
        }
        return false;
    }

    //是否触摸在指定view上面,对某个控件过滤
    public boolean isTouchView(View[] views, MotionEvent ev) {
        if (views == null || views.length == 0) {
            return false;
        }
        int[] location = new int[2];
        for (View view : views) {
            view.getLocationOnScreen(location);
            int x = location[0];
            int y = location[1];
            if (ev.getX() > x && ev.getX() < (x + view.getWidth())
                    && ev.getY() > y && ev.getY() < (y + view.getHeight())) {
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            if (isTouchView(filterViewByIds(), ev)) {
                return super.dispatchTouchEvent(ev);
            }
            if (hideSoftByEditViewIds() == null || hideSoftByEditViewIds().length == 0) {
                return super.dispatchTouchEvent(ev);
            }
            View v = getCurrentFocus();
            if (isFocusEditText(v, hideSoftByEditViewIds())) {
                KeyBoardUtils.hideInputForce(this);
                clearViewFocus(v, hideSoftByEditViewIds());
            }
        }
        return super.dispatchTouchEvent(ev);
    }


    /**
     * 传入EditText的Id
     * 没有传入的EditText不做处理
     *
     * @return id 数组
     */
    public int[] hideSoftByEditViewIds() {
        return null;
    }

    /**
     * 传入要过滤的View
     * 过滤之后点击将不会有隐藏软键盘的操作
     *
     * @return id 数组
     */
    public View[] filterViewByIds() {
        return null;
    }


    /*实现案例===============================================================================================*/
    /*

    @Override
    public int[] hideSoftByEditViewIds() {
        int[] ids = {R.id.et_company_name, R.id.et_address};
        return ids;
    }

    @Override
    public View[] filterViewByIds() {
        View[] views = {mEtCompanyName, mEtAddress};
        return views;
    }

    */

}
